package com.doubao.config;

import com.doubao.config.properties.DouBaoProperties;
import com.doubao.exception.BusinessException;
import com.volcengine.ark.runtime.model.completion.chat.*;
import com.volcengine.ark.runtime.service.ArkService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.time.Duration;
import org.springframework.util.StringUtils;

@Slf4j
@Component
@RequiredArgsConstructor
public class DoubaoClient {

    private final DouBaoProperties properties;
    private ArkService arkService;

    // 使用ConcurrentHashMap存储会话历史
    private final Map<String, List<ChatMessage>> chatHistory = new ConcurrentHashMap<>();
    private static final int MAX_HISTORY_TURNS = 10;
    private static final int MAX_TOKEN_LENGTH = 4000;  // 最大token限制
    private static final Duration HISTORY_EXPIRE_TIME = Duration.ofHours(24); // 历史记录过期时间



    @PostConstruct
    public void init() {
        // 初始化ArkService
        arkService = ArkService.builder()
                .apiKey(properties.getApiKey())
                .baseUrl(properties.getBaseUrl())
                .timeout(Duration.ofSeconds(properties.getTimeout()))
                .retryTimes(properties.getRetryTimes())
                .build();

        log.info("DoubaoClient initialized with endpointId: {}", properties.getEndpointId());

        // 启动定期清理过期历史记录的任务
        startHistoryCleanupTask();
    }

    /**
     * 发送聊天消息
     */
    public String chat(Long deviceId, String content, String systemPrompt) {
        // 参数校验
        validateParams(deviceId, content);

        String sessionId = String.valueOf(deviceId);
        List<ChatMessage> history = getOrCreateHistory(sessionId);

        try {
            // 构建消息列表
            List<ChatMessage> messages = buildMessageList(systemPrompt, history, content);

            // 创建请求
            ChatCompletionRequest request = buildChatRequest(messages);

            // 发送请求并处理响应
            return processChatResponse(request, history, content);

        } catch (Exception e) {
            log.error("Chat failed for deviceId: {}, content: {}", deviceId, content, e);
            clearHistory(sessionId); // 发生异常时清理历史记录
            throw new BusinessException("AI服务调用失败：" + e.getMessage());
        }
    }

    private void validateParams(Long deviceId, String content) {
        if (deviceId == null) {
            throw new BusinessException("设备ID不能为空");
        }
        if (!StringUtils.hasText(content)) {
            throw new BusinessException("消息内容不能为空");
        }
        if (content.length() > MAX_TOKEN_LENGTH) {
            throw new BusinessException("消息内容超过最大限制");
        }
    }

    private List<ChatMessage> buildMessageList(String systemPrompt, List<ChatMessage> history, String content) {
        List<ChatMessage> messages = new ArrayList<>();

        // 添加系统消息
        String defaultSystemPrompt = "你是豆包，是由字节跳动开发的AI助手。请保持对话连贯。";
        messages.add(ChatMessage.builder()
                .role(ChatMessageRole.SYSTEM)
                .content(systemPrompt != null ? systemPrompt : defaultSystemPrompt)
                .build());

        // 添加历史消息
        messages.addAll(history);

        // 添加用户消息
        messages.add(ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(content)
                .build());

        return messages;
    }

    private ChatCompletionRequest buildChatRequest(List<ChatMessage> messages) {
        return ChatCompletionRequest.builder()
                .model(properties.getEndpointId())
                .messages(messages)
                .temperature(0.7) // 添加温度参数控制回答的创造性
                .maxTokens(2000)   // 限制回答长度
                .build();
    }

    private String processChatResponse(ChatCompletionRequest request, List<ChatMessage> history, String content) {
        ChatCompletionResult result = arkService.createChatCompletion(request);

        if (result == null || result.getChoices() == null || result.getChoices().isEmpty()) {
            throw new BusinessException("AI服务返回为空");
        }

        ChatMessage assistantMessage = result.getChoices().get(0).getMessage();
        if (assistantMessage == null || !(assistantMessage.getContent() instanceof String)) {
            throw new BusinessException("AI回复格式错误");
        }

        String reply = (String) assistantMessage.getContent();

        // 更新历史记录
        updateHistory(history, content, reply);

        return reply;
    }

    private void updateHistory(List<ChatMessage> history, String content, String reply) {
        // 添加用户消息
        history.add(ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(content)
                .build());

        // 添加AI回复
        history.add(ChatMessage.builder()
                .role(ChatMessageRole.ASSISTANT)
                .content(reply)
                .build());

        // 维护历史记录大小
        while (history.size() > MAX_HISTORY_TURNS * 2) {
            history.remove(0);
            history.remove(0);
        }
    }

    /**
     * 获取或创建会话历史
     */
    private List<ChatMessage> getOrCreateHistory(String sessionId) {
        return chatHistory.computeIfAbsent(sessionId, k ->
            Collections.synchronizedList(new ArrayList<>()));
    }

    /**
     * 清除指定会话历史
     */
    public void clearHistory(String sessionId) {
        chatHistory.remove(sessionId);
        log.debug("Cleared chat history for session: {}", sessionId);
    }

    /**
     * 启动定期清理任务
     */
    private void startHistoryCleanupTask() {
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    clearExpiredHistory();
                } catch (Exception e) {
                    log.error("Failed to clean expired history", e);
                }
            }
        }, HISTORY_EXPIRE_TIME.toMillis(), HISTORY_EXPIRE_TIME.toMillis());
    }

    /**
     * 清理过期的历史记录
     */
    private void clearExpiredHistory() {
        log.debug("Starting cleanup of expired chat histories");
        chatHistory.clear(); // 简单实现，实际可以基于时间戳进行清理
    }
}